package com.example.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.example.gulimall.product.service.CategoryBrandRelationService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.utils.PageUtils;
import com.example.common.utils.Query;

import com.example.gulimall.product.dao.BrandDao;
import com.example.gulimall.product.entity.BrandEntity;
import com.example.gulimall.product.service.BrandService;
import org.springframework.transaction.annotation.Transactional;


@Service("brandService")
@Transactional(rollbackFor = Exception.class)
public class BrandServiceImpl extends ServiceImpl<BrandDao, BrandEntity> implements BrandService {

    @Autowired private CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String key = (String) params.get("key");
        IPage<BrandEntity> page = this.page(
                new Query<BrandEntity>().getPage(params),
                Wrappers.<BrandEntity>lambdaQuery()
                    .like(StringUtils.isNotBlank(key), BrandEntity::getName, key)
        );

        return new PageUtils(page);
    }

    @Override
    public void updateDetails(BrandEntity brand) {
        this.baseMapper.updateById(brand);

        this.categoryBrandRelationService.updateBrand(brand);
    }

    @Override
    public List<BrandEntity> getBatchById(Set<Long> brandIds) {

        if (CollectionUtils.isEmpty(brandIds)) {
            return Collections.emptyList();
        }

        List<BrandEntity> entities = this.baseMapper.selectList(
                Wrappers.<BrandEntity>lambdaQuery()
                        .in(BrandEntity::getBrandId, brandIds)
        );

        if (CollectionUtils.isEmpty(entities)) {
            return Collections.emptyList();
        }
        return entities;
    }
}